package cn.chengpengper.nacos.client.properties;

import java.util.Map;
import java.util.Objects;
import java.util.Properties;

public class SystemEnvPropertySource extends AbstractPropertySource {

    private final Map<String, String> env = System.getenv();

    @Override
    SourceType getType() {
        return SourceType.ENV;
    }

    @Override
    String getProperty(String key) {
        String resolvedName = checkPropertyName(key);
        if (Objects.isNull(resolvedName)) {
            String upperCaseKey = key.toUpperCase();
            if (!upperCaseKey.equals(key)) {
                resolvedName = checkPropertyName(upperCaseKey);
            }
        }
        if (Objects.isNull(resolvedName)) {
            return null;
        }
        return env.get(resolvedName);
    }

    /**
     * copy from https://github.com/spring-projects/spring-framework.git
     * SystemEnvironmentPropertySource
     */
    private String checkPropertyName(String name) {
        if (containsKey(name)) {
            return name;
        }

        String noDotName = name.replace('.', '_');
        if (!name.equals(noDotName) && containsKey(noDotName)) {
            return noDotName;
        }

        String noHyphenName = name.replace('-', '_');
        if (!name.equals(noHyphenName) && containsKey(noHyphenName)) {
            return noHyphenName;
        }

        String noDotNoHyphenName = noDotName.replace('-', '_');
        if (!noDotName.equals(noDotNoHyphenName) && containsKey(noDotNoHyphenName)) {
            return noDotNoHyphenName;
        }
        // Give up
        return null;
    }

    @Override
    boolean containsKey(String key) {
        return this.env.containsKey(key);
    }

    @Override
    Properties asProperties() {
        Properties cloneProperties = new Properties();
        cloneProperties.putAll(this.env);
        return cloneProperties;
    }
}
